package com.pay.paytoken.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pay.paytoken.R;
import com.pay.paytoken.base.BaseTitleActivity;
import com.pay.paytoken.paytoken.PayTokenConstant;
import com.pay.paytoken.utils.PayPwdVerifyDialog;
import com.pay.paytoken.utils.SMSVerifyDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import apiUtils.apis.account.BaseAccountAPI;
import apiUtils.apis.account.SMSSendAPI;
import apiUtils.apis.account.VerifyAccountAPI;
import apiUtils.apis.account.VerifyPayPwdAPI;
import apiUtils.apis.account.VerifySMSAPI;
import apiUtils.models.AccountStateModel;
import appUtils.LogUtil;
import appUtils.PayMD5Util;
import appUtils.PayTokenException;
import appUtils.SharedPreferencesManager;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;
import constant.AppConstants;

import static appUtils.SharedPreferencesManager.BINDING_LIST;
import static appUtils.SharedPreferencesManager.VERIFY_PHONE;
import static com.pay.paytoken.R.id.ib_pwd_visible;
import static com.pay.paytoken.paytoken.PayTokenConstant.bindtype_EXTRA;


public class BindMsgActivity extends BaseTitleActivity {

    @Bind(R.id.ed_bindmsg_usercode)
    EditText mEdBindmsgUsercode;
    @Bind(R.id.ed_bindmsg_userpwd)
    EditText mEdBindmsgUserpwd;
    @Bind(R.id.ib_pwd_visible)
    ImageButton mIbPwdVisible;
    private String mTypeString;
    private Gson gson = new Gson();
    private int mBindType = -1;
    private AccountStateModel mModel;
    private PayPwdVerifyDialog mPayPwdVerifyDialog;
    private SMSVerifyDialog mSMSVerifyDialog;

    @Override
    public int setView() {
        return R.layout.activity_bind_msg;
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPhoneUtil.getDevicePermission();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        mBindType = intent.getIntExtra(bindtype_EXTRA, -2);
    }

    @Override
    public void initView() {
        mTitleLeft.setVisibility(View.VISIBLE);
        mTitleRight.setVisibility(View.INVISIBLE);
        initWidget();
    }

    private void initWidget() {
        mTitleName.setText(String.format("%s%s", getString(R.string.binding), getString(R.string.verify)));
        String titleStr = "";
        switch (mBindType) {
            case PayTokenConstant.BINDTYPE_WALLET_REQUESTCODE:
                titleStr = getString(R.string.wallet);
                mTypeString = "wallet";
                break;
            case PayTokenConstant.BINDTYPE_SHANGHU_REQUESTCODE:
                titleStr = getString(R.string.merchants);
                mTypeString = "merchant";
                break;
            case PayTokenConstant.BINDTYPE_YUANGONG_REQUESTCODE:
                titleStr = getString(R.string.employees);
                mTypeString = "employee";
                break;
            case PayTokenConstant.BINDTYPE_GEREN_REQUESTCODE:
                titleStr = getString(R.string.personal);
                mTypeString = "personal";
                break;
            default:
                break;
        }
        mEdBindmsgUsercode.setHint(getString(R.string.please_input) + titleStr + getString(R.string.usercode));
        mEdBindmsgUserpwd.setHint(getString(R.string.please_input) + titleStr + getString(R.string.login_password));
        mEdBindmsgUserpwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (TextUtils.isEmpty(mEdBindmsgUsercode.getText().toString())
                            || TextUtils.isEmpty(mEdBindmsgUserpwd.getText().toString())) {
                        ToastUtil.showShort(R.string.account_password_cannot_empty);
                        return true;
                    }
                    verifyAccountApi();
                }
                return false;
            }
        });
    }


    @OnClick({R.id.btn_bindmsg_bind, ib_pwd_visible})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_bindmsg_bind:
                if (TextUtils.isEmpty(mEdBindmsgUsercode.getText().toString())
                        || TextUtils.isEmpty(mEdBindmsgUserpwd.getText().toString())) {
                    ToastUtil.showShort(R.string.account_password_cannot_empty);
                    return;
                }
                verifyAccountApi();
                break;
            case ib_pwd_visible:
                if (mEdBindmsgUserpwd.getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    mEdBindmsgUserpwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mIbPwdVisible.setImageResource(R.drawable.icon_pwd_visible);
                } else {
                    mEdBindmsgUserpwd.setInputType(InputType.TYPE_CLASS_TEXT |
                            InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mIbPwdVisible.setImageResource(R.drawable.icon_pwd_invisible);
                }
                mEdBindmsgUserpwd.setSelection(mEdBindmsgUserpwd.getText().toString().length());
                break;
            default:
                break;
        }

    }

    private void verifyAccountApi() {
        String userCode = mEdBindmsgUsercode.getText().toString();
        String userPwd = mEdBindmsgUserpwd.getText().toString();
        if (TextUtils.isEmpty(userCode) || TextUtils.isEmpty(userPwd)) {
            ToastUtil.showShort(R.string.account_password_cannot_empty);
            return;
        }
        String mdPwd = PayMD5Util.getMD5Lower(userPwd);
        showProgress(R.string.loadding);
        new VerifyAccountAPI(getApplicationContext()).verifyAccount(mTypeString,
                userCode, mdPwd, new BaseAccountAPI.Listener() {
                    @Override
                    public void onSuccess(final JSONObject object) {
                        try {
                            if (null != object) {
                                LogUtil.log("doVerifyAccount Success");
                                dismisProgress();
                                if (TextUtils.isEmpty(object.toString())) {
                                    return;
                                }
                                mModel = new AccountStateModel();
                                mModel.setState("1");
                                mModel.setUserAccount(mEdBindmsgUsercode.getText().toString());
                                mModel.setUserAccountId(object.getString("accountId"));
                                mModel.setUserCompanyName(object.getString("companyName"));
                                mModel.setUserPhoneNumber(object.getString("mobileNumber"));
                                mModel.setUserAccountType(mTypeString);
                                ToastUtil.showShort(object.getString("message"));
                                if (mBindType == PayTokenConstant.BINDTYPE_WALLET_REQUESTCODE) {
                                    doPayPwdVerify();
                                } else {
                                    doSmsVerify();
                                }
                            } else {
                                LogUtil.log("doVerifyAccount Failure object null");
                                ToastUtil.showShort(R.string.verify_account_failure);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            LogUtil.log("doVerifyAccount Failure JSONException");
                            ToastUtil.showShort(R.string.verify_account_failure);
                            PayTokenException.getInstance().saveExceptionFile("BindMsgActivity " +
                                    "doVerifyAccount error:" + e.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(int code, final String message) {
                        LogUtil.log("doVerifyAccount Failure");
                        dismisProgress();
                        if (!TextUtils.isEmpty(message.trim())) {
                            ToastUtil.showShort(message);
                        } else {
                            ToastUtil.showShort(R.string.verify_account_failure);
                        }
                    }
                });
    }

    private void verifyPayPwdApi(String pwd) {
        showProgress(R.string.loadding);
        new VerifyPayPwdAPI(getApplicationContext()).verifyPayPwdAccount(mTypeString,
                mModel.getUserAccountId(), pwd, new BaseAccountAPI.Listener() {
                    @Override
                    public void onSuccess(final JSONObject object) {
                        if (null != object) {
                            LogUtil.log("verifyPayPwdApi Success");
                            dismisProgress();
                            if (TextUtils.isEmpty(object.toString())) {
                                return;
                            }
                            try {
                                ToastUtil.showShort(object.getString("message"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                                ToastUtil.showShort(R.string.verify_pay_pwd_success);
                                PayTokenException.getInstance().saveExceptionFile("BindMsgActivity " +
                                        "verifyPayPwdApi error:" + e.getMessage());
                            }
                            mPayPwdVerifyDialog.dialogViewDismiss();
                            doSmsVerify();
                        } else {
                            LogUtil.log("verifyPayPwdApi Failure object null");
                            ToastUtil.showShort(R.string.verify_pay_pwd_failure);
                        }
                    }

                    @Override
                    public void onFailure(int code, final String message) {
                        LogUtil.log("verifyPayPwdApi Failure");
                        dismisProgress();
                        if (!TextUtils.isEmpty(message.trim())) {
                            ToastUtil.showShort(message);
                        } else {
                            ToastUtil.showShort(R.string.verify_pay_pwd_failure);
                        }
                    }
                });
    }

    private void sendSMSCode() {
        showProgress(R.string.loadding);
        new SMSSendAPI(getApplicationContext()).smsSendAccount(mTypeString,
                mModel.getUserAccountId(), new BaseAccountAPI.Listener() {
                    @Override
                    public void onSuccess(final JSONObject object) {
                        if (null != object) {
                            LogUtil.log("sendSMSCode Success");
                            dismisProgress();
                            if (TextUtils.isEmpty(object.toString())) {
                                return;
                            }
                            try {
                                ToastUtil.showShort(object.getString("message"));
                                mSMSVerifyDialog.startTimer();
                            } catch (JSONException e) {
                                e.printStackTrace();
                                ToastUtil.showShort(R.string.send_sms_code_success);
                                PayTokenException.getInstance().saveExceptionFile("BindMsgActivity " +
                                        "sendSMSCode error:" + e.getMessage());
                            }
                        } else {
                            LogUtil.log("sendSMSCode Failure object null");
                            ToastUtil.showShort(R.string.send_sms_code_failure);
                        }
                    }

                    @Override
                    public void onFailure(int code, final String message) {
                        LogUtil.log("sendSMSCode Failure");
                        dismisProgress();
                        if (!TextUtils.isEmpty(message.trim())) {
                            ToastUtil.showShort(message);
                        } else {
                            ToastUtil.showShort(R.string.send_sms_code_failure);
                        }
                    }
                });
    }

    private void verifySMSApi(String vCode) {
        String deviceName = Build.MODEL;
        if (TextUtils.isEmpty(mPhoneUtil.getDeviceIDStr())) {
            mPhoneUtil.getDevicePermission();
            return;
        }
        String deviceId = mPhoneUtil.getDeviceIDStr();
        showProgress(R.string.loadding);
        new VerifySMSAPI(getApplicationContext()).verifySMSAccount(mTypeString,
                mModel.getUserAccountId(), vCode, deviceId, deviceName, new BaseAccountAPI.Listener() {
                    @Override
                    public void onSuccess(final JSONObject object) {
                        try {
                            if (null != object) {
                                LogUtil.log("verifySMSApi Success");
                                dismisProgress();
                                if (TextUtils.isEmpty(object.toString())) {
                                    return;
                                }
                                ToastUtil.showShort(object.getString("message"));
                                mSharedPreferencesManager.saveString(
                                        SharedPreferencesManager.SECRET_KEY, object.getString("uuid"));
                                mSharedPreferencesManager.saveBoolean(VERIFY_PHONE, false);
                                mSharedPreferencesManager.saveInt(
                                        SharedPreferencesManager.DEFAULT_ACCOUNT_POS, 0);
                                saveAccountListDatas();
                                mSMSVerifyDialog.dialogViewDismiss();
                                setResult(AppConstants.BIND_MSG_RESULT);
                                finish();
                            } else {
                                LogUtil.log("verifySMSApi Failure object null");
                                ToastUtil.showShort(R.string.verify_sms_code_failure);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            LogUtil.log("verifySMSApi Failure JSONException");
                            ToastUtil.showShort(R.string.verify_sms_code_failure);
                            PayTokenException.getInstance().saveExceptionFile("verifySMSApi " +
                                    "sendSMSCode error:" + e.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(int code, final String message) {
                        LogUtil.log("verifySMSApi Failure");
                        dismisProgress();
                        if (!TextUtils.isEmpty(message.trim())) {
                            ToastUtil.showShort(message);
                        } else {
                            ToastUtil.showShort(R.string.verify_sms_code_failure);
                        }
                    }
                });
    }

    private void saveAccountListDatas() {
        List<AccountStateModel> mList = new ArrayList<>();
        String bindListStr = mSharedPreferencesManager.readString(BINDING_LIST, "");
        List<AccountStateModel> stateModelList = gson.fromJson(bindListStr, new TypeToken<List<AccountStateModel>>() {
        }.getType());
        if (null != stateModelList) {
            mList.addAll(stateModelList);
        }
        mList.add(mModel);
        mSharedPreferencesManager.saveString(BINDING_LIST, gson.toJson(mList));
    }

    private void doPayPwdVerify() {
        mPayPwdVerifyDialog = new PayPwdVerifyDialog(this);
        mPayPwdVerifyDialog.setTitle(String.format("%s%s", getString(R.string.binding), getString(R.string.verify)));
        PayPwdVerifyDialog.commitBtnClick commitBtnClick = new PayPwdVerifyDialog.commitBtnClick() {
            @Override
            public void onClick(String pwd) {
                if (mBindType == PayTokenConstant.BINDTYPE_WALLET_REQUESTCODE) {
                    String mdPwd = PayMD5Util.getMD5Lower(pwd);
                    verifyPayPwdApi(mdPwd);
                } else {
                    mPayPwdVerifyDialog.dialogViewDismiss();
                }
            }
        };
        mPayPwdVerifyDialog.setCommitBtnClick(commitBtnClick);
        mPayPwdVerifyDialog.showSMSVerifyDialog();
    }

    private void doSmsVerify() {
        mSMSVerifyDialog = new SMSVerifyDialog(this);
        mSMSVerifyDialog.setTitle(String.format("%s%s", getString(R.string.binding), getString(R.string.verify)));
        SMSVerifyDialog.commitBtnClick commitBtnClick = new SMSVerifyDialog.commitBtnClick() {
            @Override
            public void onClick(String vCode) {
                verifySMSApi(vCode);
            }
        };
        SMSVerifyDialog.customBtnClick customBtnClick = new SMSVerifyDialog.customBtnClick() {
            @Override
            public void onClick() {
                sendSMSCode();
            }
        };
        mSMSVerifyDialog.setCommitBtnClick(commitBtnClick);
        mSMSVerifyDialog.setCustomBtnClick(customBtnClick);
        mSMSVerifyDialog.setPhone(mModel.getUserPhoneNumber());
        mSMSVerifyDialog.showSMSVerifyDialog();
    }
}
